import {
  Button,
  Card,
  Cascader,
  Col,
  Image,
  Input,
  Pagination,
  Row,
  Space,
  Table
} from 'antd'
import { FileTextOutlined, SearchOutlined } from '@ant-design/icons'
import {
  useBrandSearch,
  useCommodityClassifySearch,
  useCommodityList
} from '@/api/query'
import { useEffect, useState } from 'react'

import { DataType } from '@/types'
import { FormattedMessage } from 'react-intl'
import type { TableColumnsType } from 'antd'
import { useAppSelector } from '@/store/hooks'
import { useNavigate } from 'react-router-dom'

export default function CommodityList() {
  const [pageNum, setPageNum] = useState(1) // 当前页
  const [pageSize, setPageSize] = useState(5) // 每页个数
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [commodityList, setCommodityList] = useState<DataType[]>([])

  // 当前商品 id
  const [brandId, setBrandId] = useState<number>(0)
  const [searchBrandId, setSearchBrandId] = useState<number>(0)
  // 当前商品的属性id
  const [productCategoryId, setProductCategoryId] = useState<number>(0)
  const [searchProductCategoryId, setSearchProductCategoryId] =
    useState<number>(0)
  // 用于搜索的商品名称
  const [productName, setProductName] = useState<string>('')
  const [searchProductName, setSearchProductName] = useState<string>('')
  // 用于搜索的商品的货号
  const [productSn, setProductSn] = useState<string>('')
  const [searchProductSn, setSearchProductSn] = useState<string>('')

  const { isLoading, data, error } = useCommodityList(pageNum, pageSize, {
    brandId: searchBrandId,
    productCategoryId: searchProductCategoryId,
    productName: searchProductName,
    productSn: searchProductSn
  })

  // 获取商品类型的检索数据
  const {
    data: dataClassify,
    isLoading: ClassifyLoading,
    isError: ClassifyError
  } = useCommodityClassifySearch()

  // 获取商品品牌检索数据
  const {
    data: dataBrand,
    isLoading: SearchLoding,
    isError: SearchError
  } = useBrandSearch()

  // 设置当前的选中的分类
  const [currentValue, setCurrentValue] = useState<number[]>([])

  //设置选中的设备
  const [currentBrand, setCurrentBrand] = useState<number[]>([])

  useEffect(() => {
    if (data) {
      const dataSource = data.list?.map((item: DataType) => ({
        ...item,
        key: item.id
      }))
      setCommodityList(dataSource)
    }
  }, [data])

  const navigate = useNavigate()
  // 获取redux数据
  const { definedLocale } = useAppSelector((state) => state.front)

  if (isLoading || SearchLoding || ClassifyLoading) {
    return <div>Loading...</div>
  }
  if (error || SearchError || ClassifyError) {
    return <div>Error: {error.message}</div>
  }

  // 复选框的选中操作
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys)
  }
  // 删除复选框的设置
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  }

  // 分页操作
  const changePage = (page: number, pageSize: number) => {
    setPageNum(page) // 改变当前页
    setPageSize(pageSize) // 改变每页个数
  }

  const edit = (record: DataType) => {
    console.log('编辑数据====', record)
  }
  const dele = (record: DataType) => {
    console.log('删除数据====', record)
  }

  // 获取选中的类型数据
  const onChangeClassify = (value: number[]) => {
    setCurrentValue(value)
    setProductCategoryId(value.length > 0 ? value[value.length - 1] : 0)
  }

  // 获取选中的品牌数据
  const onChangeBrand = (value: number[]) => {
    setBrandId(value.length > 0 ? value[0] : 0)
    setCurrentBrand(value)
  }

  // 数据的字段
  const columns: TableColumnsType<DataType> = [
    {
      title: <FormattedMessage id="commodity_brand.id" />,
      dataIndex: 'id'
    },
    {
      title: (
        <FormattedMessage id="commodity_list.commodity.img"></FormattedMessage>
      ),
      dataIndex: 'pic',
      render: (_, record) => (
        <Space>
          <Image width={100} src={record.pic} />
        </Space>
      )
    },
    {
      title: (
        <FormattedMessage id="commodity_list.commodity.name"></FormattedMessage>
      ),
      dataIndex: 'name'
    },
    {
      title: (
        <FormattedMessage id="commodity_list.commodity.price"></FormattedMessage>
      ),
      dataIndex: 'price'
    },
    {
      title: (
        <FormattedMessage id="commodity_list.commodity.productSn"></FormattedMessage>
      ),
      dataIndex: 'productSn'
    },
    {
      title: <FormattedMessage id="commodity_brand.sort"></FormattedMessage>,
      dataIndex: 'sort'
    },
    {
      title: (
        <FormattedMessage id="commodity_list.commodity.sales"></FormattedMessage>
      ),
      dataIndex: 'sale'
    },
    {
      title: <FormattedMessage id="commodity_brand.operate"></FormattedMessage>,
      dataIndex: 'operation',
      render: (_, record) => (
        <Space>
          <Button type="primary" onClick={() => edit(record)}>
            <FormattedMessage id="commodity_brand.edit"></FormattedMessage>
          </Button>
          <Button danger type="primary" onClick={() => dele(record)}>
            <FormattedMessage id="commodity_brand.delete"></FormattedMessage>
          </Button>
        </Space>
      )
    }
  ]

  // 多条件搜索
  const searchResult = () => {
    setSearchBrandId(brandId)
    setSearchProductCategoryId(productCategoryId)
    setSearchProductName(productName)
    setSearchProductSn(productSn)
  }

  const resetFilters = () => {
    setBrandId(0)
    setProductCategoryId(0)
    setProductName('')
    setProductSn('')
    setCurrentBrand([])
    setCurrentValue([])
  }

  return (
    <div>
      {/* 用于展示搜索的条件 */}
      <Card>
        {/* 显示以及操作按钮 */}
        <Row>
          <Col span={6} style={{ textAlign: 'left' }}>
            <SearchOutlined />
            <FormattedMessage id={'commodity_list.search.filtering'} />
          </Col>
          <Col span={6} style={{ textAlign: 'center' }}></Col>
          <Col span={6} style={{ textAlign: 'center' }}></Col>
          <Col span={2} style={{ textAlign: 'center' }}>
            <Button onClick={resetFilters}>
              <FormattedMessage id={'commodity_list.reset'} />
            </Button>
          </Col>
          <Col span={2} style={{ textAlign: 'center' }}>
            <Button type="primary" onClick={searchResult}>
              <FormattedMessage id={'commodity_list.search.result'} />
            </Button>
          </Col>
        </Row>
        {/* 一层搜索 */}
        <Row style={{ marginTop: '20px' }}>
          <Col span={4} style={{ textAlign: 'right', fontSize: '16px' }}>
            <FormattedMessage id={'commodity_list.input.search'} />
          </Col>
          <Col span={3} style={{ textAlign: 'center' }}>
            <Input
              value={productName}
              onChange={(event) => setProductName(event.target.value)}
            />
          </Col>
          <Col span={4} style={{ textAlign: 'right', fontSize: '16px' }}>
            <FormattedMessage id={'commodity_list.article.number'} />
          </Col>
          <Col span={3} style={{ textAlign: 'center' }}>
            <Input
              value={productSn}
              onChange={(event) => setProductSn(event.target.value)}
            />
          </Col>
          <Col span={4} style={{ textAlign: 'right', fontSize: '16px' }}></Col>
          <Col span={3} style={{ textAlign: 'center' }}></Col>
        </Row>
        {/* 二层搜索 */}
        <Row style={{ marginTop: '20px' }}>
          <Col span={4} style={{ textAlign: 'right', fontSize: '16px' }}>
            <FormattedMessage id={'commodity_list.commodity.classification'} />
          </Col>
          {/* 商品分类 */}
          <Col span={3} style={{ textAlign: 'center' }}>
            <Cascader
              options={dataClassify.newList}
              onChange={onChangeClassify}
              value={currentValue}
            />
          </Col>
          <Col span={4} style={{ textAlign: 'right', fontSize: '16px' }}>
            <FormattedMessage id={'commodity_list.commodity.brand'} />
          </Col>
          <Col span={3} style={{ textAlign: 'center' }}>
            <Cascader
              options={dataBrand.newList}
              onChange={onChangeBrand}
              value={currentBrand}
            />
          </Col>
          <Col span={4} style={{ textAlign: 'right', fontSize: '16px' }}></Col>
          <Col span={3} style={{ textAlign: 'center' }}></Col>
        </Row>
      </Card>
      {/* 添加 */}
      <Card>
        <Row>
          <Col span={6}>
            <FileTextOutlined />
            <FormattedMessage id="commodity_title.data.list"></FormattedMessage>
          </Col>
          <Col span={6}></Col>
          <Col span={6}></Col>
          <Col span={6} style={{ textAlign: 'right' }}>
            <Button
              type="default"
              onClick={() => navigate('/commodity/addCommodity')}
            >
              <FormattedMessage id="commodity_title.add"></FormattedMessage>
            </Button>
          </Col>
        </Row>
      </Card>
      {/* 表格数据 */}
      <Card>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={commodityList}
          pagination={false}
        />
        <Pagination
          total={data?.total || 0}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => {
            return definedLocale === 'zh'
              ? `总共 ${total} 条`
              : `Total ${total} items`
          }}
          onChange={changePage}
          pageSizeOptions={['5', '10', '15', '20']}
          defaultPageSize={pageSize}
          current={pageNum}
        />
      </Card>
    </div>
  )
}
